#!/bin/bash
#set -eux

APP_DIR=$(cd `dirname $0`/../;pwd)
OS_TYPE=""
. $APP_DIR/scripts/common
ACTION=$1
SERVICE=$2


function run()
{
    if [[ "$ACTION" =~ "status" ]];then
        status
        return
    fi

    if [[ "$OS_TYPE" =~ "Darwin" ]];then
        brew services $1 $2
    else
        sudo systemctl $1 $2
    fi
}

show_help()
{
    echo ""
    echo "Usage: ./deps {start|stop|status} {nats-server|redis}"
    echo ""
}

function status() {
    if [[ "$SERVICE" == "" ]]; then
        exit 1
    fi
    if [ `pgrep -n $SERVICE` ]; then
        echo -e "\033[32m[OK]\033[0m: $SERVICE is running"
    else
        echo -e "\033[32m[Failed]\033[0m: $SERVICE is not running"
    fi
}

if [[ $# -ne 2 ]] ; then
    show_help
    exit 1
fi

if [[ "$ACTION" != "start" && "$ACTION" != "stop" && "$ACTION" != "status" ]]; then
    show_help
    exit 1
fi

if [[ "$SERVICE" != "nats-server" && "$SERVICE" != "redis" ]]; then
    show_help
    exit 1
fi

PID_FILE=$APP_DIR/configs/$SERVICE.pid
LOG_FILE=$APP_DIR/logs/$SERVICE.log

if [[ "$SERVICE" == "nats-server" && "$OS_TYPE" != "Darwin" ]]; then
    if [[ "$ACTION" == "start" ]]; then
        ## run command
        echo "nohup $SERVICE>$LOG_FILE 2>&1 &"
        nohup $SERVICE>>$LOG_FILE 2>&1 &
        pid=$!
        echo "$pid"
        echo "$pid" > $PID_FILE
        rpid=`ps aux | grep $pid |grep -v "grep" | awk '{print $2}'`
        if [[ $pid != $rpid ]];then
            echo "start failly. $pid $rpid"
            # rm  $PID_FILE
            exit 1
        fi
        exit 0
    fi

    if [[ "$ACTION" == "stop" ]]; then
        echo "stop $SERVICE..."
        PID=`cat $PID_FILE`
        if [ ! -n "$PID" ]; then
            echo "pid not exist"
            exit 1;
        fi
        SUB_PIDS=`pgrep -P $PID`
        if [ -n "$SUB_PIDS" ]; then
            GRANDSON_PIDS=`pgrep -P $SUB_PIDS`
        fi

        #echo "kill $PID $SUB_PIDS $GRANDSON_PIDS"
        kill $PID $SUB_PIDS $GRANDSON_PIDS
        rm -rf $PID_FILE
        echo "stop $SERVICE ok"
        exit 0
    fi
fi

run $ACTION $SERVICE

